// 宠物管理相关 API
// 使用统一的请求封装

import request from '@/utils/request';
import { API_BASE } from '@/config/config.js';

// 获取宠物列表
export function getPetList(userId) {
  return request({
    url: '/system/pet/list',
    method: 'GET',
    data: {
      pageNum: 1,
      pageSize: 100,
      userId: userId
    }
  }).then(data => {
  
    return data;
  }).catch(err => {
  
    throw err;
  });
}

// 获取宠物详情
export function getPetDetail(petId) {
  return request({
    url: `/system/pet/${petId}`,
    method: 'GET'
  }).then(data => {
  
    return data;
  }).catch(err => {
  
    throw err;
  });
}

// 添加宠物
export function addPet(data) {
  return request({
    url: '/system/pet',
    method: 'POST',
    data
  }).then(data => {
  
    return data;
  }).catch(err => {
  
    throw err;
  });
}

// 更新宠物信息
export function updatePet(petId, data) {
  return request({
    url: '/system/pet',
    method: 'PUT',
    data: {
      ...data,
      id: petId
    }
  }).then(data => {
  
    return data;
  }).catch(err => {
  
    throw err;
  });
}

// 删除宠物
export function deletePet(petId) {
  return request({
    url: `/system/pet/${petId}`,
    method: 'DELETE'
  }).then(data => {
  
    return data;
  }).catch(err => {
  
    throw err;
  });
}

// 获取宠物健康记录
export function getPetHealthRecords(petId) {
  return request({
    url: `/system/pet/health/${petId}`,
    method: 'GET'
  }).then(data => {
  
    return data;
  }).catch(err => {
  
    throw err;
  });
}

// 获取宠物位置记录
export function getPetLocationRecords(petId) {
  return request({
    url: `/system/pet/location/${petId}`,
    method: 'GET'
  }).then(data => {
  
    return data;
  }).catch(err => {
  
    throw err;
  });
}

// 上传宠物照片
export function uploadPetPhoto(filePath, token) {
  // 由于Swagger配置了pathMapping: /dev-api，后端会自动添加这个前缀
  // 所以前端调用时不需要包含/dev-api
  const uploadUrl = `${API_BASE}/system/pet/photo`;
  
  
  
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: uploadUrl,
      filePath,
      name: 'photofile',
      header: { Authorization: 'Bearer ' + token },
      success: (res) => {
    
        try {
          const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
          if (data && data.code === 200) {
            resolve(data)
          } else {
            reject(new Error(data?.msg || '上传失败'))
          }
        } catch (e) {
          reject(new Error('解析响应失败'))
        }
      },
      fail: (err) => {
    
        reject(err)
      }
    })
  });
}